//js 调用
//jackyToken
var jackyTokenInstance;
//movie token
var movieCoinInstance;
var web3;
//构造crowd合约对象
var crowdContractAddr = "0x53a887c36ce464d8999f70f0402b33e2d3215b03";
var ownerAddr = "0xde0dcbb6bd431ff552e8baf29f823d06fdff0463";
var crowdObj;//= new web3.eth.Contract(crowdAbi, crowdContractAddr);
var acctAddr;


function formatDateTime(timeStamp) {
    var date = new Date();
    date.setTime(timeStamp * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};

//获取当前地址众筹信息
function getAdadressMovieInfo() {
    crowdObj.methods.getMvcAddr().call().then((data) => {
        console.log("data ", data);
        movieCoinInstance = new web3.eth.Contract(mvcAbi, data);
        if (movieCoinInstance != '' || movieCoinInstance != undefined) {
            console.log("load MvcInstance success !!");
            console.log(movieCoinInstance);
            let address = $("#addressId").val();

            movieCoinInstance.methods.crowInfo(address).call().then(data => {
                console.log("info... ", data);
                let amount = data.amount;
                //mvc 份额
                $("#mvcValue").html(data.amount)
                //时间戳
                $("#voteTime").html(formatDateTime(data.crowdTime));

                //totalSupply
                movieCoinInstance.methods.totalSupply().call().then(data => {
                    let totalSupply;
                    totalSupply = data;
                    $("#totalSupply").html(data);
                    $("#mvcPresent").html( amount/totalSupply*100 + "%")
                });
            });





        }
    });
}

//空投电影份额
function airDropMovieCoin(address, value) {
    //开始加载电影信息
    crowdObj.methods.getMvcAddr().call().then((data) => {
        console.log("data ", data);
        movieCoinInstance = new web3.eth.Contract(mvcAbi, data);
        if (movieCoinInstance != '' || movieCoinInstance != undefined) {
            movieCoinInstance.methods.airDrop(address, value).send({
                from: ownerAddr,
                gas: 300000
            }).then(data => {
                console.log(data);
                getAdadressMovieInfo();
            });
        }
    });
}

//获取电影信息
function loadMovieInfo() {
    //开始加载电影信息
    crowdObj.methods.getMvcAddr().call().then((data) => {
        console.log("data ", data);
        movieCoinInstance = new web3.eth.Contract(mvcAbi, data);
        if (movieCoinInstance != '' || movieCoinInstance != undefined) {
            console.log("load MvcInstance success !!");
            console.log(movieCoinInstance);
            movieCoinInstance.methods.desc().call().then(data => {
                console.log("desc ", data);
                $("#fileName").html(data);
            });
            //totalSupply
            movieCoinInstance.methods.totalSupply().call().then(data => {
                $("#totalSupply").html(data);
            });
        }
    });
}

//购买电影票
function buyTicket() {
    crowdObj.methods.getMvcAddr().call().then((data) => {
        console.log("data ", data);
        movieCoinInstance = new web3.eth.Contract(mvcAbi, data);
        movieCoinInstance.methods.ticketBooking().send({
            from: acctAddr,
            value: 20000000000000000,
            gas: 300000
        },function (error,data) {
            if(!error){
                console.log(data);
                alert("购票成功");
            }else{
                alert("购票失败！");
            }
        });
    });
}

//获取JC余额
function getJCBalance(address) {
    crowdObj.methods.getJackyTokenAddr().call().then((data) => {
        jackyTokenInstance = new web3.eth.Contract(jcAbi, data);
        if (jackyTokenInstance != '' || jackyTokenInstance != undefined) {
            jackyTokenInstance.methods.balanceOf(address).call().then((data) => {
                console.log(data);
                $("#jcBalance").html(data);
            });
        }
    });
}

//充值JC
function addJackyToken(address, value) {
    crowdObj.methods.getJackyTokenAddr().call().then((data) => {
        jackyTokenInstance = new web3.eth.Contract(jcAbi, data);
        if (jackyTokenInstance != '' || jackyTokenInstance != undefined) {
            jackyTokenInstance.methods.airDrop(address, value).send({
                from: ownerAddr,
                gas: 300000
            }).then((data) => {
                console.log(data);
                alert("充值成功！");
                getJCBalance(address);
            });
        }
    });
}

//利用JC认购MVC
function vote(accAddr, value) {
    crowdObj.methods.getJackyTokenAddr().call().then((data) => {
        jackyTokenInstance = new web3.eth.Contract(jcAbi, data);
        if (jackyTokenInstance != '' || jackyTokenInstance != undefined) {
            jackyTokenInstance.methods.transfer(ownerAddr, value).send({
                from: accAddr,
                gas: 300000
            }).then((data) => {
                console.log("转账成功");
                airDropMovieCoin(acctAddr, value);
                getJCBalance(accAddr);
            });
        }
    });
}


$(function () {
    //弹窗
    $('#myModal').modal();
    //构造web3对象
    //var web3 = new Web3(new Web3.providers.WebProvider("http://localhost:8545"));
    web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:8546"));
    web3.eth.getAccounts(function (e, r) {
        console.log(e, r);
    });
    crowdObj = new web3.eth.Contract(crowdAbi, crowdContractAddr);
    console.log("crowdInstance ", crowdObj);

    //获取电影众筹实例
    crowdObj.methods.getMvcAddr().call((error, result) => {
        if (!error) {
            movieCoinInstance = new web3.eth.Contract(mvcAbi, result);
            if (movieCoinInstance != '' || movieCoinInstance != undefined) {
                console.log("load MvcInstance success !!");
                console.log(movieCoinInstance);
            }
        } else {
            console.log("load MvcInstance failed !!");
        }
    });
    //获取jackytoken 实例
    crowdObj.methods.getJackyTokenAddr().call().then((result) => {
        jackyTokenInstance = new web3.eth.Contract(jcAbi, result);
        if (jackyTokenInstance != '' || jackyTokenInstance != undefined) {
            console.log("load jackyTokenInstance success !!");
            console.log(jackyTokenInstance);
        }
    });


    loadMovieInfo();


    // movieCoinInstance.methods.desc().call((error,result) => {
    //     if(!error){
    //         console.log(result);
    //     }else{
    //         console.log("load movie desc filed");
    //     }
    // });


    //登陆按钮被点击
    $(".Login").on("click", function () {
        acctAddr = $("#addressId").val();
        console.log("get acct:", acctAddr);
        getAdadressMovieInfo();
        getJCBalance(acctAddr);
        $(".close_win").click();
    });
    //充值Jc
    $(".Recharge").on("click", function () {
        let value = $("#getJc").val();
        console.log(value);
        addJackyToken(acctAddr, value);
    });

    //投票处理- 此时可以认为合约地址都已经拿到,kcc合约对象，mvc合约地址
    $(".Vote").on("click", function () {
        let voteValue = $("#voteValue").val();
        if (voteValue < 100) {
            alert("至少认购100以上");
            return;
        }
        vote(acctAddr, voteValue);
    });

    $("#buy").on('click', () => {
        buyTicket();
    })

});